extends Area2D

signal hit

export var speed=400  # player move speed
var screen_size # windows screen size

var target=Vector2()
var velocity=Vector2()


# Called when the node enters the scene tree for the first time.
func _ready():
	hide()
	screen_size=get_viewport_rect().size
	pass # Replace with function body.

func start(pos):
	position=pos
	
	target=pos
	$CollisionShape2D.disabled=false
	show()
	
func _input(event):
	if event is InputEventScreenTouch and event.is_pressed():
		pass
	if event is InputEventScreenDrag:
		target=event.position
		pass		

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	#if Input.is_action_pressed("ui_down"):
	#	velocity.y+=1
	#elif Input.is_action_pressed("ui_up"):
	#	velocity.y-=1
	#elif Input.is_action_pressed("ui_left"):
	#	velocity.x-=1
	#elif Input.is_action_pressed("ui_right"):
	#	velocity.x+=1
	
	#if position.distance_to(target)>10:
	#	velocity=(target-position).normalized()*speed
	#else:
	#	velocity.x=0
	#	velocity.y=0
	
	if velocity.length()>0:
		velocity=velocity.normalized() * speed
		$AnimatedSprite.play()
	else:
		$AnimatedSprite.stop()
	
	position += velocity*delta
	position.x=clamp(position.x,0,screen_size.x)
	position.y=clamp(position.y,0,screen_size.y)


	pass

func update_velocity(vec):
	velocity=vec
	if velocity.y>=velocity.x:
		$AnimatedSprite.animation="up"
		$AnimatedSprite.flip_v=velocity.y>0
	else:
		$AnimatedSprite.animation="right"
		$AnimatedSprite.flip_v=false
		$AnimatedSprite.flip_h=velocity.x>0
	pass


func _on_Player_body_entered(body):
	hide()
	emit_signal("hit")
	$CollisionShape2D.set_deferred("disabled",true)
	pass # Replace with function body.
